<template>
  <view class="search">
    <!-- 搜索框开始 -->
    <view class="search_row">
      <input :value="iptValue" @input="handleInput" placeholder="请输入您要搜索的产品名称" />
      <button @tap="handleCancel" v-show="isFocus" type="primary" size="mini">取消</button>
    </view>
    <!-- 搜索框 结束 -->
    <!-- 搜索结果开始 -->
    <view class="search_result_content">
      <navigator class="search_result_item" v-for="(item, index) in goods" :key="item.goods_id" :url="'../../pages/goods_detail/goods_detail?goods_id=' + item.goods_id">
        <!-- 商品名称 -->
        {{ item.goods_name }}
      </navigator>
    </view>
    <!-- 搜索结果结束 -->
  </view>
</template>

<script>
import regeneratorRuntime from '../../lib/runtime/runtime.js';
import { request } from '../../request/request.js';
export default {
  data() {
    return {
      // 搜索到的产品数组
      goods: [],
      // 按钮的显示和隐藏
      isFocus: false,
      //输入框的值
      iptValue: '',
      // 定时器ID
      timeID: 0
    };
  },
  methods: {
    /* 搜索产品 */
    async qSearch(query) {
      var _me = this;
      var res = await request({
        url: 'https://api-hmugo-web.itheima.net/api/public/v1/goods/search',
        data: {
          query: query
        }
      });
      // console.log(res.data.message.goods);
      _me.goods = res.data.message.goods;
    },
    /* 输入内容 */
    handleInput(e) {
      var _me = this;
      var value = e.detail.value;
      // 输入的值是否全是空格
      if (!!value.trim()) {
        // 不是空格
        _me.iptValue = value.trim();
        _me.isFocus = true;
        clearTimeout(_me.timeID);
        _me.timeID = setTimeout(function() {
          _me.qSearch(_me.iptValue);
        }, 1000);
      } else {
        // 全是空格
        _me.iptValue = value;
        _me.isFocus = false;
        _me.goods = [];
      }
    },
    /* 取消 */
    handleCancel(e) {
      var _me = this;
      _me.iptValue = '';
      _me.isFocus = false;
      _me.goods = [];
    }
  }
};
</script>

<style lang="scss">
page {
  background-color: #edece8;
}
.search {
  padding: 10rpx;
  /* 搜索框开始 */
  .search_row {
    display: flex;
    height: 60rpx;
    input {
      height: 100%;
      flex: 1;
      background-color: #fff;
      padding-left: 30rpx;
    }
    button {
      width: 110rpx;
      height: 100%;
      font-size: 26rpx;
      font-weight: normal;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 0;
      // margin: 0 20rpx;
    }
  }
  /* 搜索框结束 */
  /* 搜索结果开始 */
  .search_result_content {
    margin-top: 30rpx;
    .search_result_item {
      background-color: #fff;
      border-bottom: 1rpx solid #ccc;
      font-size: 26rpx;
      padding: 15rpx 10rpx;
      width: 97%;
      /* 让内容只显示一行 多出的内容用...表示 */
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  /* 搜索结果开始 */
}
</style>
